package com.wangjw.tuling.netty.rpc.server;

import com.wangjw.tuling.netty.rpc.common.RpcBuilder;
import com.wangjw.tuling.netty.rpc.common.RpcRequest;
import com.wangjw.tuling.netty.rpc.common.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by wangjianwen on 2018/12/11.
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<RpcRequest> {

    private RpcBuilder rpcBuilder;

    public NettyServerHandler(RpcBuilder rpcBuilder) {
        this.rpcBuilder = rpcBuilder;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest rpcRequest) throws Exception {
        RpcResponse response = rpcBuilder.invokeService(rpcRequest);
        ctx.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
